package net.didactylos.helpline.data;

import javax.mail.internet.InternetAddress;

import net.sourceforge.stripes.util.Log;

import org.hibernate.Session;

public class ContactManager
{
	private static final Log log = Log.getInstance(ContactManager.class);
	
	private Session session;
	
	public ContactManager(Session session)
	{
		super();
		this.session = session;
	}

	/**
	 * Finds a contact matching the specified address. If none is
	 * found, a new contact is created, persisted and returned.
	 * 
	 * @param from
	 * @return
	 */
	public Contact findContact(InternetAddress from)
	{
		Contact contact = (Contact) session
		.createQuery("from Contact as contact where contact.emailAddress=?")
		.setString(0, from.getAddress())
		.uniqueResult();
		
		if (contact == null)
		{
			contact = Contact.contactForAddress(from);
			session.save(contact);
		}
		return contact;
	}
}
